package research.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 很早之前写的一个操作多个数据库的简易工具类（现在都用ORM之类的东西了，这种方式的场景非常少了）
 * 
 * 链接数据库还是需要对应的jar
 * ORACLE：ojdbc6或更高版本
 * MSSQL：sqljdbc4或更高版本
 *
 */
public class CreateDBConn {
	
	public static final String MSSQL="MSSQL";
	public static final String ORACLE="ORACLE";
	
	private ReadFile readFile=null;
	private Connection dbConn;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	private String dbType="";
	

	
	public CreateDBConn(String dbType,String readFilePath){
		this.dbType=dbType;
		readFile = new ReadFile(dbType,readFilePath);
	}
	
	public void CreateConnection() {
		
		String dbURL="";
		if (dbType.equals(MSSQL)) {
			
			DBMSSQLEntity dbEntity=(DBMSSQLEntity)readFile.ReadIni();
			dbURL = "jdbc:sqlserver://"+dbEntity.getServerName()+"; DatabaseName="+dbEntity.getDatabase();
			
			try {
				dbConn = DriverManager.getConnection(dbURL, dbEntity.getUser(), dbEntity.getPwd());
				System.out.println("Connection Successful!"); 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		else {
			
			DBOracleEntity dbEntity=(DBOracleEntity)readFile.ReadIni();
			
			try {
				dbConn = DriverManager.getConnection(dbEntity.getServerName(), dbEntity.getUser(), dbEntity.getPwd());
				System.out.println("Connection Successful!"); 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public ResultSet Search(String sql){
		try {
			ps =dbConn.prepareStatement(sql);
			rs = ps.executeQuery();
			return rs;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	/**
	 * 
	 * @param sql
	 * @return int 返回1表示成功
	 */
	public int Operate(String sql){
		try {
			ps =dbConn.prepareStatement(sql);
			int re = ps.executeUpdate();
			if (dbType.equals(ORACLE)) {
				ps.getConnection().commit();
			}
			return re;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}
	
	public void CloseConn() throws SQLException{
		dbConn.close();
	}
}
